import java.awt.FileDialog;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

import org.omg.PortableInterceptor.SUCCESSFUL;


public class EventWindow implements ActionListener, WindowListener, Serializable
{
	private static final long serialVersionUID = 2682883208946368630L;
		/*TO DO LIST
		 * -Be Able to go "BACK" to NewEventWindow(pass address to the object, to directly access its EventClass)
		 * -Letter Gen
		 *  * Duplicate must be prevented
		 * 
		 */
		//Variables
		Event Event;
		Boolean tmp=false;
		String saveString=null;
		JComboBox<String> nameList=new JComboBox();
		
	    //Shared
		Calendar curTime = Calendar.getInstance();	//For clock
		SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss MM-dd-yyyy"); //For clock
			
		//Window Specific
		JFrame mainFrame=new JFrame();
		JFrame gdad=null;
		
		//Input
		JButton btnAdd=new JButton("Add"), btnFin=new JButton("Finished"),btnEdit=new JButton("Edit Event"), btnExtend = new JButton("Show More"), btnDelete = new JButton ("Delete");
		JPanel Screen = new ImagePanel(new ImageIcon("img/RemoteApp_D3.gif").getImage());
		JComboBox<String> CourseBox=new JComboBox(),SectionBox=new JComboBox();
		JTextField Name=new JTextField(), IDno=new JTextField();
		JLabel NameL=new JLabel("Name:"), IDL=new JLabel("ID Number:"), CourseL=new JLabel("Course:"), SectionL=new JLabel("Section:");
		Boolean onExtend = false;
		
		//Icon
		Image imgLogo = Toolkit.getDefaultToolkit().createImage("img/Dlsu.png");
		Image imgDown = Toolkit.getDefaultToolkit().createImage("img/down.png");
		Image imgUp = Toolkit.getDefaultToolkit().createImage("img/up.png");
		Image imgDel = Toolkit.getDefaultToolkit().createImage("img/del.png");
		Image imgAdd = Toolkit.getDefaultToolkit().createImage("img/add.png");
		Image imgEdit = Toolkit.getDefaultToolkit().createImage("img/editEvent.png");
		Image imgFin = Toolkit.getDefaultToolkit().createImage("img/fin.png");
		ImageIcon logo, down, up, del, add, fin, edit;
		
	EventWindow(JFrame grandfather, Event a)
	{
		//Variables
		Event=a;
		
		Image newimg = imgDown.getScaledInstance(18, 18, java.awt.Image.SCALE_SMOOTH) ;  
		down = new ImageIcon( newimg );
		Image newimg2 = imgUp.getScaledInstance(18, 18, java.awt.Image.SCALE_SMOOTH) ;  
		up = new ImageIcon( newimg2 );
		Image newimg3 = imgDel.getScaledInstance(18, 18, java.awt.Image.SCALE_SMOOTH) ;  
		del = new ImageIcon( newimg3 );
		Image newimg4 = imgAdd.getScaledInstance(18, 18, java.awt.Image.SCALE_SMOOTH) ;  
		add = new ImageIcon( newimg4 );
		Image newimg5 = imgEdit.getScaledInstance(18, 18, java.awt.Image.SCALE_SMOOTH) ;  
		edit = new ImageIcon( newimg5 );
		Image newimg6 = imgFin.getScaledInstance(18, 18, java.awt.Image.SCALE_SMOOTH) ;  
		fin = new ImageIcon( newimg6 );
		
		//Window Specifics
		this.gdad=grandfather;
		mainFrame.setIconImage(imgLogo);
		mainFrame.addWindowListener(this);
		mainFrame.setLayout(null);
		mainFrame.setSize(440,200);
		mainFrame.setResizable(false);
		mainFrame.setLocationRelativeTo(null);
		mainFrame.setVisible(true);
		mainFrame.add(Screen);
		mainFrame.setDefaultCloseOperation(mainFrame.DISPOSE_ON_CLOSE);
		
		//Screen
		Screen.setLayout(null);
		Screen.setBounds(0,0,440,210);
		
		//JComponents
		onExtend = false;
		btnAdd.setBounds(310,13,115,25);
		btnFin.setBounds(310,90,115,25);
		btnEdit.setBounds(310,53,115,25);
		btnExtend.setBounds(160, 135, 120, 20);
		btnDelete.setBounds(310,175,115,25);
		
		CourseBox.setBounds(20,90,190,25);
		for(int i=0;i<Event.Courses.size();i++)
			CourseBox.addItem(Event.Courses.get(i).CourseCode);
		//CourseBox.setEditable(true);
		SectionBox.setBounds(220,90,80,25);
		if(!Event.Courses.isEmpty())
			for(int i=0;i<Event.Courses.get(0).Sections.size();i++)
				SectionBox.addItem(Event.Courses.get(0).Sections.get(i).toString());
		//SectionBox.setEditable(true);
		nameList.setBounds(20,175,280,25);
		for(int i=0;i<Event.StudentList.size();i++)
			nameList.addItem(Event.StudentList.get(i).ID + " " + Event.StudentList.get(i).Name + " - " + Event.StudentList.get(i).CourseCode + " " +Event.StudentList.get(i).Section);
		
		Name.setBounds(20,35,190,25);
		IDno.setBounds(220,35,80,25);
		
		NameL.setBounds(20,8,150,25);
		IDL.setBounds(220,8,100,25);
		CourseL.setBounds(20,63,160,25);
		SectionL.setBounds(220,63,100,25);
		
		btnExtend.setIcon(down);
		btnDelete.setIcon(del);
		btnAdd.setIcon(add);
		btnFin.setIcon(fin);
		btnEdit.setIcon(edit);
		
		//Adding to Screen
		Screen.add(btnAdd);
		Screen.add(btnFin);
		Screen.add(btnEdit);
		Screen.add(CourseBox);
		Screen.add(SectionBox);
		Screen.add(Name);
		Screen.add(IDno);
		Screen.add(NameL);
		Screen.add(IDL);
		Screen.add(CourseL);
		Screen.add(SectionL);
		Screen.add(btnExtend);
		Screen.add(btnDelete);
		Screen.add(nameList);
		
		//ActionListeners
		CourseBox.addActionListener(this);
		btnAdd.addActionListener(this);
		btnFin.addActionListener(this);
		btnEdit.addActionListener(this);
		btnExtend.addActionListener(this);
		btnDelete.addActionListener(this);
	}
	
	public void actionPerformed(ActionEvent arg0)
	{
		Object source = arg0.getSource();
		if(source==CourseBox)
		{
			switch(arg0.getActionCommand())
			{
			case "comboBoxChanged":
				if(CourseBox.getSelectedIndex()>=0)
				{
					SectionBox.removeAllItems();
					for(int i=0;i<Event.Courses.get(CourseBox.getSelectedIndex()).Sections.size();i++)
						SectionBox.addItem(Event.Courses.get(CourseBox.getSelectedIndex()).Sections.get(i).toString());
				}
				break;
			}
		}
		else if(source==btnAdd)
		{	
			try
			{
				if(Integer.parseInt(IDno.getText().toString())>9999999&&Integer.parseInt(IDno.getText().toString())<100000000)
					tmp=false;
				else
					tmp=true;
			}
			catch( Exception e )
			{
				tmp=true;
			}
			
			if(Name.getText().equals(""))
			{
				JOptionPane.showMessageDialog(null, "ERROR: No Name inputted", "ERROR", JOptionPane.ERROR_MESSAGE);
			}
			else if(IDno.getText().equals(""))
			{
				JOptionPane.showMessageDialog(null, "ERROR: No id number inputted", "ERROR", JOptionPane.ERROR_MESSAGE);
			}
			else if(tmp)
			{
				JOptionPane.showMessageDialog(null, "ERROR: Invalid ID Number", "ERROR", JOptionPane.ERROR_MESSAGE);
			}
			else if(CourseBox.getSelectedIndex()<0&&!Event.Courses.isEmpty())
			{
				System.out.print("ERROR: NO COURSE SELECTED!\n");
			}
			else if(SectionBox.getSelectedIndex()<0&&!Event.Courses.isEmpty())
			{
				System.out.print("ERROR: NO SECTION SELECTED!\n");
			}
			else
			{
				if(Event.Courses.isEmpty())
				{
					Event.AddStudent(new Student(Integer.parseInt(IDno.getText()),Name.getText()));
				}
				else
				{
					Event.AddStudent(new Student(Integer.parseInt(IDno.getText()),Name.getText(),CourseBox.getSelectedItem().toString(),SectionBox.getSelectedItem().toString()));
				}
				nameList.removeAllItems();
				for(Student tempStudent:Event.StudentList)
					nameList.addItem(tempStudent.ID + " " + tempStudent.Name + " - " + tempStudent.CourseCode + " " + tempStudent.Section);
				nameList.setSelectedIndex(nameList.getItemCount()-1);
				IDno.setText("");
				Name.setText("");
			}
			
		}
		else if(source==btnFin)
		{
			FileOutputStream fileStreamOut = null;
			ObjectOutputStream objectStreamOut = null;
			System.out.print("Opening FileDialog");
			 FileDialog fd = new  FileDialog(mainFrame, "Save To", FileDialog.SAVE);
			 fd.setVisible(true);
			 
			 System.out.print("Saving...");
			 //SAVE PORTION GOES HERE
             try
             {
            	 if(!fd.getFile().substring(fd.getFile().indexOf('.')).equals(".adcreate")){
     			 	saveString=fd.getDirectory()+fd.getFile()+".adcreate";
     			 }
     			 else{
     				 saveString=fd.getDirectory()+fd.getFile();
     			 }
            	 fileStreamOut= new FileOutputStream(saveString);
            	 objectStreamOut= new ObjectOutputStream(fileStreamOut);
//            	 objectStreamOut.writeInt(Event.EventID);
//            	 objectStreamOut.writeChars(Event.EventTitle);
//            	 objectStreamOut.writeObject(Event.Courses);
//            	 objectStreamOut.writeObject(Event.StudentList);
            	 objectStreamOut.writeObject(Event);
    			 System.out.print("Save Successful. loading main menu...");
    			 
             }
    		catch(Exception e) {
    		}
            finally {
    			try {
    				objectStreamOut.flush();
    				objectStreamOut.close();
    				fileStreamOut.close();	
    				gdad.setVisible(true);
    				mainFrame.dispose();
    			}
    			catch (Exception e) {
    			}
    		}
			 
		}
		else if(source==btnEdit)
		{
			new NewEvent(mainFrame,Event,true);
			mainFrame.dispose();
		}
		else if(source==btnExtend)
		{
			if(onExtend){
				onExtend = false;
				btnExtend.setText("Show Less");
				btnExtend.setIcon(up);
				mainFrame.setSize(440,240);
			}
			else{
				onExtend = true;
				btnExtend.setText("Show More");
				btnExtend.setIcon(down);
				mainFrame.setSize(440,200);
			}
		}
		else if(source==btnDelete){
			if(nameList.getItemCount()>0)
			{
				Event.StudentList.remove(nameList.getSelectedIndex());
				nameList.removeItemAt(nameList.getSelectedIndex());
			}
			else
				JOptionPane.showMessageDialog(null, "ERROR: Can't delete, No names detected", "ERROR", JOptionPane.ERROR_MESSAGE);

		}
	}

	public void windowActivated(WindowEvent arg0)
	{
		
	}

	public void windowClosed(WindowEvent arg0)
	{
		
	}

	public void windowClosing(WindowEvent arg0)
	{
		gdad.setVisible(true);
		mainFrame.dispose();
	}

	public void windowDeactivated(WindowEvent arg0)
	{
		
	}

	public void windowDeiconified(WindowEvent arg0)
	{
		
	}

	public void windowIconified(WindowEvent arg0)
	{
		
	}

	public void windowOpened(WindowEvent arg0)
	{
		
	}

}
